import React, { useState, useEffect, useContext } from "react";
import { useHistory } from "react-router-dom";
import { toJS } from "mobx";
import { Toast, List, InfiniteScroll, SwipeAction, Popup, Button } from "antd-mobile";
import moment from "moment";
import { observer } from "mobx-react-lite";

import ChatInboxCard from "../../../components/ChatInboxCard";
import Collection from "../../../components/Collection";
import { resolveMsgFormContent } from "../../../utils/index";

import { MySdkStoreContext } from "../../../context";
import { ConversationType } from "../../../constants";

import "./style.scss";

const ConverList = observer(() => {
  const history = useHistory();
  const mySdkStore = useContext(MySdkStoreContext);
  const [collectionCompProps, setCollectCompProps] = useState({ visible: false });
  const [showMoreActionPopup, setShowMoreActionPopup] = useState({ visible: false });
  const [groups, setGroups] = useState({ topModeId: 0, shieldModeId: 0 });
  const [topModeList, setTopModeList] = useState([]);
  const [pagination, setPagination] = useState({ pageIndex: 1, next: 0 });

  //获取分组信息
  const getConversationGroups = async () => {
    const group = await mySdkStore.sdk.queryConversationGroups();
    const topModeId = group.find((item) => item.groupName.indexOf("置顶") > -1)?.id;
    const shieldModeId = group.find( (item) => item.groupName.indexOf('免打扰') > -1)?.id;
    setGroups({ topModeId, shieldModeId });
    return { topModeId, shieldModeId }
  }
  // 获取置顶会话列表
  const getTankTopList = async () => {
    const { topModeId } = await getConversationGroups();
    if (topModeId) {
      const { list } = await mySdkStore.sdk.queryConversationListByGroup({
        pageIndex: 1,
        pageSize: 100,
        groupId: topModeId,
      });
      const newConvers = list.map((conver) => {
        const {
          gmtCreate,
          lastMsgContentType,
          lastMsgContent,
          lastMsgSenderId,
          lastMsgRecallStatus,
        } = conver;

        // 处理单条会话数据
        const lastMsg =
          lastMsgRecallStatus > 0
            ? `${
                lastMsgSenderId === mySdkStore.mockConfig.userId ? "你" : "对方"
              }撤回了一条消息`
            : resolveMsgFormContent(lastMsgContentType, lastMsgContent);

        return {
          ...conver,
          gmtCreate: moment(gmtCreate).format("YYYY/MM/DD HH:mm:ss"),
          lastMsg,
        };
      });
      mySdkStore.updateConverList([...mySdkStore.converList, ...newConvers]);
      setTopModeList(newConvers);
      return newConvers;
    } else {
      return [];
    }
  };

  useEffect(async () => {
    if (!(mySdkStore.converList && mySdkStore.converList.length)) {
      Toast.show({
        icon: "loading",
        content: "加载中…",
      });
      const topModeList = await getTankTopList();
      await getConver(1, topModeList);
    }
  }, []);

  // useEffect(async () => {
  //   console.log(mySdkStore.converList);
  // }, [mySdkStore.converList]);

  // useEffect(() => {
    // 重置onNewMessage回调，将新消息展示在回话列表中
    // mySdkStore.sdk.onNewMessage = (msgs) => {
    //   mySdkStore.onNewMessage(msgs);
    //   const lastMsg = msgs[msgs.length - 1];
    //   const {
    //     cid,
    //     msgType,
    //     msgContent,
    //     msgId,
    //     lastMsgRecallStatus,
    //     lastMsgSenderId,
    //   } = lastMsg;
    //   setConverList((preConverList) => {
    //     const matchIndex = preConverList.findIndex(
    //       (conver) => conver.cid === cid
    //     );
    //     if (matchIndex >= 0) {
    //       const lastMsg =
    //         lastMsgRecallStatus > 0
    //           ? `${
    //               lastMsgSenderId === mySdkStore.mockConfig.userId
    //                 ? "你"
    //                 : "对方"
    //             }撤回了一条消息`
    //           : resolveMsgFormContent(msgType, msgContent);

    //       const matchItem = preConverList[matchIndex];
    //       const { unReadCount, bizParams } = matchItem;
    //       preConverList[matchIndex] = {
    //         ...matchItem,
    //         unReadCount: bizParams.is_default_read
    //           ? unReadCount
    //           : unReadCount + msgs.length,
    //         lastMsgId: msgId,
    //         lastMsgContentType: msgType,
    //         lastMsg,
    //         gmtModified: new Date().valueOf(),
    //         bizParams: { ...bizParams, is_hidden: "0" },
    //       };
    //       if (bizParams.is_hidden === "1") {
    //         mySdkStore.sdk.addConversationUserMark({
    //           cid,
    //           marks: [{ propertyName: "is_hidden", propertyValue: 0 }],
    //         });
    //       }
    //     }
    //     return [...preConverList];
    //   });
    // };

    // 群组信息变更回调
    // mySdkStore.sdk.onGroupInfoChange = (updateGroupRepones) => {
    //   const { cid, updateType, name, logoUrl } = updateGroupRepones;
    //   setConverList((preConverList) => {
    //     const matchIndex = preConverList.findIndex(
    //       (conver) => conver.cid === cid
    //     );
    //     if (matchIndex > -1) {
    //       const matchItem = preConverList[matchIndex];
    //       if (updateType === "name") {
    //         preConverList[matchIndex] = { ...matchItem, name };
    //       } else if (updateType === "logo") {
    //         preConverList[matchIndex] = { ...matchItem, logoUrl };
    //       }
    //     }
    //     return [...preConverList];
    //   });
    // };

    // return () => {
    //   mySdkStore.sdk.onNewMessage = mySdkStore.onNewMessage;
    // };
  // }, [mySdkStore.sdk]);

  const conversationEdit = (action, converInfo) => {
    const { lastMsgId, cid, bizParams = {} } = converInfo;
    console.log("conversationEdit>>>", action, converInfo);
    const { val } = action;
    if (!mySdkStore.sdk) return;
    if (val === "allRead") {
      //消息游标已读
      mySdkStore.sdk.changeMessagesStatus({
        type: "read",
        cursorMsgId: lastMsgId,
        cid,
      });

      const newConverList = [...mySdkStore.converList];
      const matchIndex = newConverList.findIndex(
        (conver) => conver.cid === cid
      );
      if (matchIndex > -1) {
        const matchItem = newConverList[matchIndex];
        newConverList[matchIndex] = { ...matchItem, unReadCount: 0 };
      }
      mySdkStore.updateConverList(newConverList);
    }
    if (val === "is_default_read") {
      //会话新消息默认已读
      const newDefaultReadState = !bizParams.is_default_read;
      mySdkStore.sdk.setConversationTag({
        cid,
        type: "is_default_read",
        value: newDefaultReadState,
      });

      const newConverList = [...mySdkStore.converList];
      const matchIndex = newConverList.findIndex(
        (conver) => conver.cid === cid
      );
      if (matchIndex > -1) {
        const matchItem = newConverList[matchIndex];
        const { bizParams = {} } = matchItem;
        newConverList[matchIndex] = {
          ...matchItem,
          bizParams: { ...bizParams, is_default_read: newDefaultReadState },
        };
      }
      mySdkStore.updateConverList(newConverList);
    }
  };

  // 获取会话列表
  const getConver = async (pageIndex, topList?) => {
    return mySdkStore.sdk
      .queryConversationList({ pageIndex, pageSize: 10, type: "all" })
      .then((data) => {
        const { next, list } = data;
        setPagination({ pageIndex, next: +next });
        const newConvers = list.map((conver) => {
            const {
              gmtCreate,
              lastMsgContentType,
              lastMsgContent,
              lastMsgSenderId,
              lastMsgRecallStatus,
            } = conver;
            const lastMsg =
              lastMsgRecallStatus > 0
                ? `${
                    lastMsgSenderId === mySdkStore.mockConfig.userId
                      ? "你"
                      : "对方"
                  }撤回了一条消息`
                : resolveMsgFormContent(lastMsgContentType, lastMsgContent);
            return {
              ...conver,
              gmtCreate: moment(gmtCreate).format("YYYY/MM/DD HH:mm:ss"),
              lastMsg,
            };
          }).filter(
            (item) =>
              !(topList || topModeList).find(({ cid }) => item.cid === cid)
          );
        mySdkStore.updateConverList([...mySdkStore.converList, ...newConvers]);
        Toast.clear();
      });
  };

  const getNextData = async () => {
    await getConver(pagination.pageIndex + 1);
  };

  const toChatPage = (cid) => {
    history.push({ pathname: `/chatDetail/${cid}`, search: `?debug=true` });
  }

  // 左滑点击“置顶”或“取消置顶”事件
  const handleToggleToGroup = async (cid, rowData) => {
    if (!rowData.topMode) {
      // 置顶
      rowData.topMode = true;
      await mySdkStore.sdk.addConversationToGroups({ cid, groupId: groups.topModeId });

      mySdkStore.updateConverList([rowData, ...mySdkStore.converList.filter((item) => item.cid !== cid)]);

      setTopModeList([...topModeList, rowData]);
    } else {
      // 取消置顶
      rowData.topMode = false;
      await mySdkStore.sdk.removeConversationFromGroups({
        cid,
        groupId: groups.topModeId,
      });
      mySdkStore.updateConverList([...mySdkStore.converList.filter((item) => item.cid !== cid), rowData]);

      setTopModeList((converList) => {
        return converList.filter((item) => item.cid !== cid);
      });
    }
  };

  // 点击“移除回话”事件
  const handleRemoveConversation = async (cid) => {
    const res = await mySdkStore.sdk.addConversationUserMark({
      cid,
      marks: [{ propertyName: "is_hidden", propertyValue: 1 }],
    });
    if (res?.errorMessage) {
      Toast.show(res.errorMessage);
      return;
    }

    mySdkStore.updateConverList([...mySdkStore.converList.filter((item) => item.cid !== cid)]);
  };

  // 选择“标记”后回调
  const handleCollectionOk = async (tagCodes, cid) => {
    try {
      await mySdkStore.sdk.collectSession({ cid, tagCodes });
      Toast.show("标记成功");
      setCollectCompProps({ visible: false });
    } catch (e) {
      console.log(e);
    }
  };

  // 点击“标记”事件，展示“选择标记”界面
  const handleCollect = (cid) => {
    setCollectCompProps({
      visible: true,
      cid,
      onOk: (tagCode) => handleCollectionOk(tagCode, cid),
      onClose: () => setCollectCompProps({ visible: false }),
    });
  };

  const showMoreAction = (cid, lastMsgId) => {
    setShowMoreActionPopup({visible: true, cid, lastMsgId });
  }

  const handleAllRead = (cid, lastMsgId) => {
    if(!(lastMsgId && cid)) return;
    mySdkStore.sdk.changeMessagesStatus({
      type: "read",
      cursorMsgId: lastMsgId,
      cid,
    }).then(data => {
      setShowMoreActionPopup({visible: false, cid: '', lastMsgId: ''});
    });
  };

  const handleModeChange = async (cid) => {
    if (!groups.shieldModeId) {
      return;
    }

    const newConverList = [...mySdkStore.converList];
    const matchConverIndex = newConverList.findIndex(conver => conver.cid === cid);
    if(matchConverIndex < 0) return;
    const matchConver = newConverList[matchConverIndex]
    const { shieldMode } = matchConver;
    const api = shieldMode
      ? 'removeConversationFromGroups'
      : 'addConversationToGroups';
    await mySdkStore.sdk[api]({ cid, groupId: groups.shieldModeId });
    newConverList[matchConverIndex] = {...matchConver, shieldMode: !shieldMode,}
    mySdkStore.updateConverList(newConverList);

    setShowMoreActionPopup({visible: false, cid: '', lastMsgId: ''});
  };

  const handleCloseConversation = (cid) => {
    mySdkStore.sdk.closeConversation({ cid}).then(data => {
      Toast.show({
        icon: 'success',
        content: '解散会话成功',
      });

      const newConverList = [...mySdkStore.converList];
      const matchConverIndex = newConverList.findIndex(conver => conver.cid === cid);
      if(matchConverIndex < 0) return;
      newConverList.splice(matchConverIndex, 1);
      mySdkStore.updateConverList(newConverList);

      setShowMoreActionPopup({visible: false, cid: '', lastMsgId: ''});
    });
  };

  const handleAllDelete = (cid, lastMsgId) => {
    mySdkStore.sdk.changeMessagesStatus({
      type: "delete",
      cursorMsgId: lastMsgId,
      cid,
    }).then(data => {
      Toast.show({
        icon: 'success',
        content: '清空聊天记录成功',
      });
      setShowMoreActionPopup({visible: false, cid: '', lastMsgId: ''});
    });
  };

  // 渲染单条会话方法
  const renderRow = (rowData) => {
    const { cid, bizParams = {}, lastMsgId } = rowData;
    const { is_default_read } = bizParams;
    const collectAction = {
      key: "collect",
      text: "收藏",
      color: "warning",
      onClick: () => handleCollect(cid),
    };
    const stayTopAction = {
      key: "stayTop",
      text: !rowData.topMode ? "置顶" : "取消置顶",
      color: "primary",
      onClick: (e) => {
        e.stopPropagation();
        handleToggleToGroup(rowData.cid, rowData);
      },
    };
    const deleteAction = {
      key: "delete",
      text: "移除",
      color: "danger",
      onClick: () => handleRemoveConversation(cid),
    };
    const moreAction = {
      key: "more",
      text: "更多",
      color: "light",
      onClick: () => showMoreAction(cid, lastMsgId),
    };

    const rightActions =
      rowData.type === ConversationType.Notify
        ? [collectAction, stayTopAction]
        : [collectAction, stayTopAction, deleteAction, moreAction];
    if (mySdkStore.isHideSomeFunctions) {
      rightActions.shift();
    }
    return (
      <SwipeAction rightActions={rightActions}>
        <ChatInboxCard
          key={cid}
          onCardClicked={() => toChatPage(cid)}
          {...rowData}
          isDefaultRead={is_default_read}
          editFunc={(action) => conversationEdit(action, rowData)}
        />
      </SwipeAction>
    );
  };

  return (
    <>
      <div className="converList">
        <List style={{ "--border-inner": 0, "--border-bottom": 0 }}>
          {mySdkStore.converList
            .filter((item) => item.bizParams?.is_hidden !== "1")
            .map((item) => {
              const conver = toJS(item);
              return (
              <List.Item key={conver.cid}>{renderRow(conver)}</List.Item>
            )}
            )}
        </List>
        <InfiniteScroll loadMore={getNextData} hasMore={pagination.next > 1} />
      </div>
      <Popup
        visible={collectionCompProps.visible || showMoreActionPopup.visible}
        destroyOnClose
        onMaskClick={() => {
          setCollectCompProps({ visible: false });
          setShowMoreActionPopup({visible: false, cid: '', lastMsgId: ''});
        }}
        bodyClassName={ collectionCompProps.visible ? "selectorOperationsBarComponnet-collectionPopup" : ''}
      >
        {collectionCompProps.visible ? <Collection {...collectionCompProps} /> : null}
        {showMoreActionPopup.visible ? <div>
          <Button block onClick={() => handleModeChange(showMoreActionPopup.cid)}>消息免打扰</Button>
          {
            showMoreActionPopup.lastMsgId ?<>
              <Button block onClick={() => handleAllRead(showMoreActionPopup.cid, showMoreActionPopup.lastMsgId)}>全部已读</Button>
              <Button block onClick={() => handleAllDelete(showMoreActionPopup.cid, showMoreActionPopup.lastMsgId)}>清空聊天记录</Button>
            </> : null
          }
          <Button block onClick={() => handleCloseConversation(showMoreActionPopup.cid)}>解散会话</Button>
        </div>
         : null}
      </Popup>
    </>
  );
});

export default ConverList;
